// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const TcbRouter = require('tcb-router')
const db = cloud.database()
const newsCollection = db.collection('news')

// 云函数入口函数
exports.main = async (event, context) => {

  const app = new TcbRouter({
    event
  })
// 模糊搜索
  app.router('list', async (ctx, next) => {
    const keyWord = event.keyWord
    let w = {}
    // 判断用户输入的值是否为空
    if (keyWord.trim() != '') {
      w = {
        content: db.RegExp({
          regexp: keyWord,
          options: 'i'
        })
      }
    }
    let newsList = await newsCollection
      .where(w)
      .skip(event.start)
      .limit(event.count)
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        return res.data
      })
    ctx.body = newsList
  })

  // 查询文章详情页数据
  app.router('detail', async (ctx, next) => {
    let newsId = event.newsId
    // 根据文章id查询单条文章数据
    let detail = await newsCollection.where({
        _id: newsId
      })
      .get()
      .then(res => {
        return res.data
      })
    // 评论查询
    // 取出
    let commentList = await db.collection('news-comment').where({
        newsId
      })
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        return res.data
      })

    ctx.body = {
      detail,
      commentList
    }
  })


 

  return app.serve()

    // return {
  //   event,
  //   openid: wxContext.OPENID,
  //   appid: wxContext.APPID,
  //   unionid: wxContext.UNIONID,
  // }
}